package com.leetcode.string;

public class ReverseWord {
    public static String reverseWord(String s){
        String[] words = s.trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for(int i = words.length - 1; i >= 0; i--){
            sb.append(words[i]).append(" ");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String reverseWord2(String s){
        s = s.trim();
        int i = s.length() - 1, j = i;
        StringBuilder sb = new StringBuilder();
        while(i >= 0){
            while(i >= 0 && s.charAt(i) != ' '){
                i--;
            }
            sb.append(s.substring(i + 1, j + 1)).append(" ");
            while(i >= 0 && s.charAt(i) == ' '){
                i--;
            }
            j = i;
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static void main(String[] args) {
        String res = reverseWord2("the sky is blue");
        System.out.println(res);
    }
}
